package com.example.swimmingpool.service.question;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.example.swimmingpool.entity.notice.Notice;
import com.example.swimmingpool.entity.question.Question;
import com.mongodb.client.result.UpdateResult;
import jakarta.annotation.Resource;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionService {
    @Resource
    private MongoTemplate mongoTemplate;

    public List<Question> getQuestions() {
        return mongoTemplate.findAll(Question.class);
    }

    public boolean addQuestion(Question question) {
        var now = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATETIME_PATTERN);
        question.setCreateTime(now);
        var res = mongoTemplate.insert(question);
        return StrUtil.isNotBlank(res.getId());
    }

    public boolean removeQuestion(Question question) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(question.getId())));
        return mongoTemplate.remove(query, Question.class).getDeletedCount() > 0;

    }

    public boolean updateQuestion(Question question) {
        Update update = new Update();
        update.set("type", question.getType());
        Query query = new Query(Criteria.where("_id").is(question.getId()));
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Question.class);
        return updateResult.getModifiedCount() > 0;
    }
}
